package org.softmed.ATComm.server;

import org.restlet.Restlet;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.softmed.ATComm.ATControlFacade;

/**
 * Resource which has only one representation.
 * 
 */
public class SerialPortRestlet extends Restlet {

	private ATControlFacade atControl;

	public SerialPortRestlet(ATControlFacade atControl) {
		this.atControl = atControl;
	}

	@Override
	public void handle(Request request, Response response) {
		try {
			String methodName = request.getMethod().getName();
			if (methodName.equals("PUT") || methodName.equals("POST")) {

				Representation entity = request.getEntity();
				if (entity == null) {
					// TODO read parameter from http method and change serial
					// port
					response.setEntity("ERROR CONFIGURING VIA PARAMETERS NOT IMPLEMENTED YET ", MediaType.TEXT_PLAIN);
					return;

				} else if (entity.getMediaType().includes(MediaType.TEXT_PLAIN)) {
					String port = entity.getText();
					atControl.setSerialPortName(port);
					response.setEntity("CHANGED SERIAL PORT TO " + port,
							MediaType.TEXT_PLAIN);
					return;
				} else {
					response.setEntity("ERROR UNSUPPORTED MEDIA TYPE "
							+ entity.getMediaType(), MediaType.TEXT_PLAIN);
					return;
				}
			} else if (methodName.equals("GET")) {
				String port = atControl.getSerialPortName();
				port = (port == null ? "" : port);

				response.setEntity(port, MediaType.TEXT_PLAIN);
				return;
			} else {
				response.setEntity("ERROR UNSUPPORTED HTTP METHOD "
						+ methodName, MediaType.TEXT_PLAIN);
				return;
			}

		} catch (Throwable t) {
			t.printStackTrace();
			response.setEntity("EXCEPTION ERROR", MediaType.TEXT_PLAIN);
			return;
		}

//		response.setEntity("SUCESS", MediaType.TEXT_PLAIN);
	}
}
